//
//  CalculatorATableViewCell.m
//  Waiguofang
//
//  Created by waiguofang on 15/4/28.
//
//

#import "CalculatorATableViewCell.h"
#import "UIView+circular.h"

@interface CalculatorATableViewCell()
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;

@end
@implementation CalculatorATableViewCell

- (void)awakeFromNib {
    self.housePrice.delegate = self;
    self.firstPrice.delegate = self;
    
    [self.saveBtn viewToCircular];
   
    [self calculatorAction];
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([self.housePrice.text length] && [self.firstPrice.text length]) {
        float hp = [self.housePrice.text floatValue];
        float fp = [self.firstPrice.text floatValue]/100;
        float result = hp*fp;
        self.firstPriceLabel.text = [NSString stringWithFormat:@"%.2f",result];
    }
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (IBAction)calcukatorButton:(UIButton *)sender {
    [self calculatorAction];
}

- (void)calculatorAction
{
    if ([self.housePrice.text length] && [self.firstPrice.text length] && [self.lendRate.text length] &&[self.loanYears.text length] ) {
        float housePrice = [self.housePrice.text floatValue];
        float firstPrice = [self.firstPrice.text floatValue]/100.0;
        float loanPrice = housePrice *(1-firstPrice);
        float loanMonths = [self.loanYears.text floatValue]*12;
        float lendRate = [self.lendRate.text floatValue]/100.0/12.0;
        float x = pow(1+lendRate, loanMonths) ;
        
        float monthlyPayment = loanPrice*lendRate*x /(x-1);
        float totalInterest = monthlyPayment*loanMonths - loanPrice;
        
        NSString *loanPriceStr = [NSString stringWithFormat:@"%.2f",loanPrice];
        NSString *monthlyPaymentStr = [NSString stringWithFormat:@"%.2f",monthlyPayment];
        NSString *totalInterestStr = [NSString stringWithFormat:@"%.2f",totalInterest];
        
        [self.delegate calculatorResultWithTotalLoanPrice:loanPriceStr monthlyPayment:monthlyPaymentStr andTotalInterest:totalInterestStr];
        
    }

}
@end
